//
//  GTStatus.swift
//  swiftWEIbo
//
//  Created by mac－gt on 15/11/27.
//  Copyright © 2015年 mac－gt. All rights reserved.
//

import UIKit

import SDWebImage
class GTStatus: NSObject{
    var user: GTUser?
    var created_at: String?
    var id: Int = 0
    var text: String?
    var source: String?
    var reposts_count: Int=0
    var comments_count: Int=0
    var attitudes_count: Int=0
    var picURLs: [NSURL]?{
          return retweeted_status == nil ? storePictureUrls : retweeted_status?.storePictureUrls
    }
    var rowHeight: CGFloat?
    var retweeted_status: GTStatus?
    var storePictureUrls: [NSURL]?
   
    var pic_urls: [[String: AnyObject]]?{
        didSet{
            let counts=pic_urls?.count ?? 0
            if counts==0{
                return
            }
            storePictureUrls=[NSURL]()
            for dict in pic_urls!{
                let value=dict["thumbnail_pic"] as! String
                storePictureUrls?.append(NSURL(string: value)!)
            }
        }
    }
 
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override func setValue(value: AnyObject?, forKey key: String) {
        if key=="user"{
            if let dict=value as? [String:AnyObject]{
                user=GTUser(dict: dict)
            }
            return
    }
      else  if key=="retweeted_status"{
    
            if let dict=value as? [String:AnyObject]{
                retweeted_status=GTStatus(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    override var description: String {
        let propries=["retweeted_status","created_at","id","text","source","reposts_count","comments_count","attitudes_count","pic_urls","user"]
        
        return "\(dictionaryWithValuesForKeys(propries))"
    }
    class func loadStatus(since_id:Int,max_id:Int,finshed:(list:[GTStatus]?,error:NSError?)->()){
        GTNetworking.sharedInsatance.loadStatus(since_id, max_id: max_id) { (resut, error) -> () in
            if error != nil || resut==nil{
                finshed(list: nil, error: error!)
                return
            }
            if let array=resut?["statuses"] as? [[String: AnyObject]]{
                var list=[GTStatus]()
                for dict in array{
                    list.append(GTStatus(dict: dict))
                }
                cacheImage(list, finshed: finshed)
                
                finshed(list: list, error: nil)
            }else{
                finshed(list: nil, error: nil)
            }

        }
    }
    class func cacheImage(list:[GTStatus],finshed:(list:[GTStatus]?,error:NSError?)->()){
        var length:CGFloat=0
        let group=dispatch_group_create()

        for status in list{
            guard let urls=status.picURLs else{
                continue
            }
            if urls.count==1{
                let url=urls[0]
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    dispatch_group_leave(group)
                    if error != nil{
                        print("下载出错")
                        return
                    }
                    if let data=UIImagePNGRepresentation(image){
                        length += CGFloat(data.length)
                    }
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("下载所有图片：\(length/1024/1024)")
            finshed(list:list, error: nil)
        }
    }
}
